package cn.com.connext.scrm.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cuisuqiang
 * @version 1.0
 * @说明 对象操纵高级方法
 */
public class ObjectUtil {

    private static final Logger log = LoggerFactory.getLogger(ObjectUtil.class);

    private ObjectUtil() {
    }

    /**
     * 返回一个对象的属性和属性值
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> getProperty(Object entityName) {
        Map<String, String> map = new HashMap<>();
        try {
            Class c = entityName.getClass();
            // 获得对象属性
            Field field[] = c.getDeclaredFields();
            for (Field f : field) {
                Object v = invokeMethod(entityName, f.getName());
                map.put(f.getName(), v.toString());
            }
        } catch (Exception e) {
            log.error("getProperty error: ", e);
            map = null;
        }
        return map;
    }

    /**
     * 获得对象属性的值
     */
    @SuppressWarnings("unchecked")
    private static Object invokeMethod(Object owner, String methodName) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class ownerClass = owner.getClass();
        methodName = methodName.substring(0, 1).toUpperCase()
            + methodName.substring(1);
        Method method = ownerClass.getMethod("get" + methodName);
        return method.invoke(owner);
    }
}
